/**
 * Created with IntelliJ IDEA.
 * User: zzl
 * Date: 12-12-2
 * To change this template use File | Settings | File Templates.
 */
(function ($, undefined) {

    var _nextId = 0;

    var SelectGrid = function (input, options) {
        this._id = ++_nextId;
        this.$input = $(input);
        this.options = options;
        this.show();
    };

    var proto = { constructor: SelectGrid };
    SelectGrid.prototype = proto;

    proto.show = function () {
        var me = this;

        var html = '<div class="selectGridContainer">' +
            '<table class="selectGrid"><tbody></tbody></table>' +
            '</div>';

        var $selectGrid = $(html).appendTo($(document.body));
        me.$selectGrid = $selectGrid;
        me.setItems(me.options.items);

        var pos = me.options.pos;
        if (typeof(pos) == 'function') {
            pos = pos();
        }
        if (!pos) {
            pos = {};
        }
        if (!pos.top) {
            pos.top = me.$input.offset().top;
            if (me.options.upside) {
                pos.top -= $selectGrid.outerHeight();
            }
            else {
                pos.top += me.$input.outerHeight() - 1;
            }
        }
        if (!pos.left) {
            pos.left = me.$input.offset().left;
        }

        var offset = me.options.offset || {left: 0, top: 0};
        pos.left += offset.left;
        pos.top += offset.top;

        $selectGrid.css('left', pos.left + 'px');
        $selectGrid.css('top', pos.top + 'px');

        $selectGrid.on('mousedown', '.selectGrid td', function (e) {
            me.onTdMouseDown(this, e);
        });

        $selectGrid.on('mousedown', function (e) {
            e.stopPropagation();
            e.preventDefault();
        });
        //
        $(document).on('mousedown.selectGrid.' + me._id, function (e) {
            me.onDocumentMouseDown(e);
        });

//        me.$input.on('blur.selectGrid.' + me._id, function() {
//            me.hide();
//        });

    };

    proto.setItems = function (items) {
        var me = this;
        var html = me.buildGridHtml(items);
        me.$selectGrid.find('.selectGrid tbody').html(html);
    };

    proto.buildGridHtml = function (items) {
        var me = this;
        var html = '';
        var n;

        var colCount = me.options.colCount;
        var arr = items;
        if (me.options.colFirst) {
            arr = [];
            var rowCount = Math.ceil(items.length / colCount);
            for (var row = 0; row < rowCount; ++row) {
                for (var col = 0; col < colCount; ++col) {
                    n = col * rowCount + row;
                    if (n < items.length) {
                        arr.push(items[n]);
                    }
                }
            }
        }
        var defaultItemRenderer = function (item) {
            return '<td>' + item + '</td>';
        };
        var itemRenderer = me.options.itemRenderer || defaultItemRenderer;
        for (n = 0; n < arr.length; n++) {
            if (n % colCount == 0) {
                if (n > 0) {
                    html += '</tr>';
                }
                html += '<tr>';
            }
            var item = arr[n];
            var disabled = false;
            if (typeof(item) == 'object') {
                disabled = item.disabled;
                item = item.value;
            }
            var itemHtml = itemRenderer(item);
            if (itemHtml === undefined) {
                itemHtml = defaultItemRenderer(item);
            }
            html += itemHtml;
        }
        for (n = 0; n < arr.length % colCount; n++) {
            html += '<td></td>';
        }
        html += '</tr>';
        return html;
    };

    proto.onTdMouseDown = function (td, e) {
        var me = this;
        if (e.which != 1) {
            return;
        }
        e.preventDefault();
        me.options.selectedCallback(jsex.trim($(td).text()));
        me.hide();
    };

    proto.onDocumentMouseDown = function (e) {
        var me = this;
        if (e.target == me.$input[0]) {// || me.$selectGrid.has(e.target).length) {
            return;
        }
        me.hide();
    };

    proto.hide = function () {
        var me = this;
        me.$selectGrid.remove();
        $(document).off('mousedown.selectGrid.' + me._id);
        me.$input.off('blur.selectGrid.' + me._id);
        if(me.options.autoDispose) {
            me.$input.removeData('selectGrid');
        }
    };

    proto.getContainer = function () {
        var me = this;
        return me.$selectGrid[0];
    };

    $.fn.selectGrid = $.addPluginFn('selectGrid', SelectGrid, {
        autoDispose: true
    });

})(jQuery);